package org.ma5d;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.calendar.AnnualCalendar;

public class ExcludeTest {
    public static void main(String[] args) throws SchedulerException, InterruptedException {
        // 1. 定义例外
        AnnualCalendar holidays = new AnnualCalendar();
        // 2024年元旦不执行
        Calendar newYear = new GregorianCalendar(2024, Calendar.JANUARY, 1);
        holidays.setDayExcluded(newYear, true);
        // 2024年中秋不执行
        Calendar middleAutum = new GregorianCalendar(2024, Calendar.SEPTEMBER, 17);
        holidays.setDayExcluded(middleAutum, false);

        // 定义 jobDetail
        JobDetail jobDetail = JobBuilder.newJob(ExcludeJob.class).withIdentity("ExcludeJobName", "ExcludeJobGroup").build();

        Trigger trigger = TriggerBuilder.newTrigger()
        .withIdentity("ExcludeTriggerName", "ExcludeTriggerGroup")
        .withSchedule(CronScheduleBuilder.cronSchedule("*/2 * * * * ?"))
        .modifiedByCalendar("holidays")
        .build();

        // 1.定义调度器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        // 2.将自定义的Calender添加到Scheduler中
        scheduler.addCalendar("holidays", holidays, false, false);
        // 3. 设置任务触发器，由触发器进行分派任务
        scheduler.scheduleJob(jobDetail, trigger);
        scheduler.start();
        
        TimeUnit.SECONDS.sleep(20);
        scheduler.shutdown();
    }

    public static class ExcludeJob implements Job {
        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            System.out.println(LocalDateTime.now());
        }
    }
}
